package com.bnzj.cloud.business.core.persistence.repository;

import com.bnzj.cloud.business.core.persistence.entity.SysRoleUser;
import com.bnzj.core.persistence.repository.BaseRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface SysRoleUserRepository extends BaseRepository<SysRoleUser, Long> {

    @Query(value = "select * from bnz_sys_role_user where user_id = ?1", nativeQuery = true)
    public List<SysRoleUser> findSysRoleUserByUserId(Long userId);

    @Modifying
    @Query(value = "delete from bnz_sys_role_user where user_id=?1", nativeQuery = true)
    public void deleteByUserId(Long userId);

    @Modifying
    @Query(value = "delete from bnz_sys_role_user  where role_id=?1", nativeQuery = true)
    public void deleteByRoleId(Long roleId);

    @Query(value = "SELECT r.role_id FROM bnz_sys_role_user r WHERE r.user_id =?1", nativeQuery = true)
    List<Long> findRoleIdsByUserId(Long userId);


    @Query(value = "SELECT r.user_id FROM bnz_sys_role_user r WHERE r.role_id =?1", nativeQuery = true)
    List<Long> findUserIdsByRoleId(Long roleId);

    //根据角色code查询拥有该角色的用户的账号
    @Query(value = "SELECT GROUP_CONCAT(u.account) FROM bnz_sys_user u left join bnz_sys_role_user ru on u.id = ru.user_id left join bnz_sys_role r on ru.role_id = r.id where r.`code` = ?1", nativeQuery = true)
    String findAccountsByRoleCode(String roleCode);

}
